//getJsApiData.js
'use strict';
const fs = require('fs');
const request = require('request');
const qs = require('querystring');
// const getWebToken = require('./getWebToken');
const sha1 = require('sha1');


//获取noncestr
function getNonceStr () {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for(var i = 0; i < 16; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
}
//获取timestamp
function getTimestamp() {
    return new Date().valueOf();
}

// sha1加密
function getSign(jsApiTicket, noncestr, timestamp, url) {
    let data = {
        'jsapi_ticket': jsApiTicket,
        'noncestr': noncestr,
        'timestamp': timestamp,
        'url': url
    };
    var sortData = "jsapi_ticket=" + jsApiTicket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;

    return sha1(sortData);
}

//返回数据分别为sign, timestamp, noncestr
function getJsApiData(clientUrl,token,ticket) {

    var getToken = token;
    let noncestr = getNonceStr();
    let timestamp = parseInt(getTimestamp()/1000);

    var signature = getSign(ticket, noncestr, timestamp, clientUrl);
    // console.log(ticket)
    return [signature, timestamp, noncestr , ticket ,getToken];

}


module.exports = getJsApiData;